var express = require('express');
var router = express.Router();
const fs = require('fs');
const path = require('path');
const { send } = require('process');

const query = require('../conn/conn');

const send_sms = require('../lib/sendphone');

const jwt = require('jsonwebtoken');
const { log } = require('console');

router.get('/getcode', function (req, res, next) {
  fs.writeFile(path.join(__dirname, '..', 'temp', req.query.phone), send_sms(req.query.phone), 'utf8', err => {
    if (err) console.log(err);
    res.send({ msg: '验证码已发送', success: 1 });
  });
});

router.post('/register', async (req, res, next) => {

  await fs.readFile(path.join(__dirname, '..', 'temp', req.body.phone), 'utf8', (err, data) => {

    if (err) {
      console.log(err);
      res.send({ success: 0, msg: '提交的手机号与验证手机号码不符', error: 101 });

    } else if (req.body.code === data) {

      let userphone = req.body.phone;
      let password = req.body.password;

      new Promise(async function (resolve, reject) {
        let result = await query(`select * from users where phone='${userphone}'`);
        console.log(result.length);
        if (result.length) {
          reject();
        } else {
          resolve();
        }

      }).then(() => {
        let result1 = query(`INSERT INTO users ( ${'`' + 'phone' + '`'}, ${'`' + 'password' + '`'}) VALUES ( '${userphone}', '${password}')`);

        res.send({ success: 1, msg: '注册成功' })
      }).catch(() => [
        res.send({ success: 0, msg: '账号已存在' })
      ])

      fs.unlink(path.join(__dirname, '..', 'temp', req.body.phone), async err => {
        if (err) console.log(err);
        console.log('文件已删除');
      });
    } else {
      res.send({ success: 0, msg: '验证码不正确', error: 102 });
    }
  })

});

router.post('/login', async (req, res, next) => {
  const { phone, password } = req.body;

  let result = await query(`select * from users where phone='${phone}' and password='${password}'`);

  if (result.length) { // 判断是否查询到了数据

    const userInfo = {
      phone: phone,
      loginTime: Date.now()
    };
    // 生成一个token发给前端
    let token = 'Bearer ' + jwt.sign(userInfo, 'doc2138', { expiresIn: 60 * 60 * 24 });

    return res.send({
      msg: '登陆成功',
      success: 1,
      token
    });


  }
  return res.send({
    msg: '登陆失败',
    success: 0
  });
})

router.post('/getlogin', (req, res, next) => {
  let token = req.cookies.token;
  jwt.verify(token, 'doc2138', (err, data) => {
    if (err) console.log(err);
    console.log(data);
  })
})

module.exports = router;
